package com.time.hellotime.components.task;

import android.app.Activity;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Spannable;
import android.view.View;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.AMapUtils;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.BitmapDescriptor;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.amap.api.maps2d.model.MyLocationStyle;
import com.time.hellotime.R;
import com.time.hellotime.base.BaseActivity;
import com.time.hellotime.utils.SpanFormatter;
import com.time.hellotime.utils.ToastUtils;
import com.yanzhenjie.nohttp.Logger;

/**
 * Created by Bing on 2017/11/24.
 * E-mail is tx16bing@163.com
 */

public class LookMapActivity extends BaseActivity implements AMap.OnMyLocationChangeListener,
        AMapLocationListener, AMap.InfoWindowAdapter {

    private static final String EXTRA_MAP_TITLE = "extra_map_title";
    private static final String EXTRA_TARGET_LATITUDE = "extra_target_latitude";
    private static final String EXTRA_TARGET_LONGITUDE = "extra_target_longitude";

    private MapView mapView;
    private AMap mMap;
    private TextView tvTip;

    private MyLocationStyle mLocationStyle;
    private double mLatitude, mLongitude;

    public static void start(Activity mContext, String address, String latitude, String longitude) {
        Intent intent = new Intent(mContext, LookMapActivity.class);
        intent.putExtra(EXTRA_MAP_TITLE, address);
        intent.putExtra(EXTRA_TARGET_LATITUDE, latitude);
        intent.putExtra(EXTRA_TARGET_LONGITUDE, longitude);
        mContext.startActivity(intent);

    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_look_map, getIntent().getStringExtra(EXTRA_MAP_TITLE));

        mLatitude = Double.parseDouble(getIntent().getStringExtra(EXTRA_TARGET_LATITUDE));
        mLongitude = Double.parseDouble(getIntent().getStringExtra(EXTRA_TARGET_LONGITUDE));

        assignViews(savedInstanceState);
        initLocationStyle();
        createLocationRequest();
    }

    private void assignViews(Bundle state) {
        tvTip = findView(R.id.tv_look_map_tip);
        mapView = findView(R.id.time_map);
        mapView.onCreate(state);
        if (mMap == null) {
            mMap = mapView.getMap();
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        mapView.onSaveInstanceState(outState);
    }

    private void initLocationStyle() {
        mLocationStyle = new MyLocationStyle();//初始化定位蓝点样式类myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE);//连续定位、且将视角移动到地图中心点，定位点依照设备方向旋转，并且会跟随设备移动。（1秒1次定位）如果不设置myLocationType，默认也会执行此种模式。
        mLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_SHOW);
        mLocationStyle.showMyLocation(true);
        mLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.drawable.iv_map_location_me));
//        mLocationStyle.strokeColor(R.color.colorPrimary);
//        mLocationStyle.radiusFillColor(R.color.colorPrimary);
//        mLocationStyle.interval(5000); //设置连续定位模式下的定位间隔，只在连续定位模式下生效，单次定位模式下不会生效。单位为毫秒。
        mMap.setMyLocationStyle(mLocationStyle);//设置定位蓝点的Style
        mMap.getUiSettings().setMyLocationButtonEnabled(true);//设置默认定位按钮是否显示，非必需设置。
        mMap.setMyLocationEnabled(true);// 设置为true表示启动显示定位蓝点，false表示隐藏定位蓝点并不进行定位，默认是false。
        mMap.setOnMyLocationChangeListener(this);
        mMap.setInfoWindowAdapter(this);
    }

    protected void createLocationRequest() {

        // 初始化请求
        AMapLocationClient locationRequest = new AMapLocationClient(getApplicationContext());

        // 设置回调监听
        locationRequest.setLocationListener(this);

        // 初始化参数集
        AMapLocationClientOption mLocationOption = new AMapLocationClientOption();

        // 高精度定位模式，省电模式， 仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);

        // 是否返回地址信息
        mLocationOption.setNeedAddress(true);

        // 设置重定位时间间隔
        mLocationOption.setInterval(5000);

        mLocationOption.setOnceLocation(true);

        // 设置参数集
        locationRequest.setLocationOption(mLocationOption);

        locationRequest.startLocation();
    }

    @Override
    public void onResume() {
        super.onResume();
        mapView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        mapView.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }

    @Override
    public void onMyLocationChange(Location location) {
        //  定位回调
        if (location == null) {
            return;
        }
//        mLatitude = location.getLatitude();
//        mLongitude = location.getLongitude();
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation == null || aMapLocation.getErrorCode() != 0) {
            ToastUtils.showShort("定位失败");
            return;
        }

        Logger.i("Current user postion is lat : " + aMapLocation.getLatitude() +
                " and lon : " + aMapLocation.getLongitude());

        mMap.clear();
        Marker marker = mMap.addMarker(getMarkerOptions(
                aMapLocation.getLatitude(),
                aMapLocation.getLongitude(),
                R.drawable.iv_map_location_me,
                "我"));
        marker.showInfoWindow();

        Marker targetMarker = mMap.addMarker(getMarkerOptions(
                mLatitude,
                mLongitude,
                R.drawable.iv_map_location_destination,
                "目的地"));
        targetMarker.showInfoWindow();

        float calculate = AMapUtils.calculateLineDistance(new LatLng(aMapLocation.getLatitude(),
                aMapLocation.getLongitude()), new LatLng(mLatitude, mLongitude));
        int distance = (int) (calculate + 0.5);
        Spannable cSpannable = SpanFormatter.getColoredSpannable(this, distance + "", R.color.colorThirdPrimary);
        tvTip.setText(SpanFormatter.format(getString(R.string.map_distance_target_tip), cSpannable));
    }

    //自定义一个图钉，并且设置图标，当我们点击图钉时，显示设置的信息
    private MarkerOptions getMarkerOptions(double latitude, double longitude, int resId, String markerTip) {
        //设置图钉选项
        MarkerOptions options = new MarkerOptions();
        //图标
        options.icon(BitmapDescriptorFactory.fromResource(resId));
        //位置
        options.position(new LatLng(latitude, longitude));
        StringBuffer buffer = new StringBuffer();
        buffer.append(markerTip);
        //标题
        options.title(buffer.toString());
        return options;
    }

    /**
     * 自定义info window窗口的 info window事件回调
     */
    @Override
    public View getInfoWindow(Marker marker) {
        View infoWindow = getLayoutInflater().inflate(
                R.layout.custom_info_window, null);
        render(marker, infoWindow);
        return infoWindow;
    }


    @Override
    public View getInfoContents(Marker marker) {
        return null;
    }

    /**
     * 自定义info window窗口
     */
    public void render(Marker marker, View view) {
        String title = marker.getTitle();
        TextView titleUi = ((TextView) view.findViewById(R.id.tv_info_window_title));
        if (title != null) {
            titleUi.setText(title);
        }
    }

}
